package cn.xxstudy.blog.controller.admin

import cn.xxstudy.blog.bean.FileInfo
import cn.xxstudy.blog.util.logger
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.util.*
import javax.servlet.http.HttpServletRequest

/**
 * 作者：wuxinxi on 2020/12/2
 * 包名：cn.xxstudy.blog.controller.admin
 * TODO:上传图片
 */
@RestController
@RequestMapping("/file")
class ManagerImgUploadController {

    //上传路径
    private val folder = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\upload\\"

    @PostMapping
    fun uploadImg(request: HttpServletRequest,
                  @RequestParam(value = "editormd-image-file", required = false) file: MultipartFile): FileInfo {
        val fileFolder = File(folder)
        if (!fileFolder.exists()) {
            fileFolder.mkdirs()
        }
        val fileName = file.originalFilename
        val localFile = File(folder, fileName!!)
        if (localFile.exists()) {
            localFile.delete()
        }
        file.transferTo(localFile)
        return FileInfo(url = request.requestURL.substring(0, request.requestURL.lastIndexOf("/")) + "/upload/" + fileName)
    }

}